<template>
  <div class="merchant-layout">
    <!-- 侧边栏 -->
    <div class="merchant-sidebar" :class="{ 'is-collapsed': isCollapse }">
      <div class="merchant-logo p-4">
        <router-link to="/merchant/dashboard">
          饱<span>了么</span>商家版
        </router-link>
      </div>

      <el-menu
        :default-active="activeMenu"
        class="merchant-menu"
        router
        :collapse="isCollapse"
      >
        <el-menu-item index="/merchant/dashboard">
          <el-icon><DataBoard /></el-icon>
          <template #title>仪表盘</template>
        </el-menu-item>

        <el-menu-item index="/merchant/store">
          <el-icon><Shop /></el-icon>
          <template #title>店铺管理</template>
        </el-menu-item>

        <el-menu-item index="/merchant/categories">
          <el-icon><Collection /></el-icon>
          <template #title>分类管理</template>
        </el-menu-item>

        <el-menu-item index="/merchant/products">
          <el-icon><Goods /></el-icon>
          <template #title>商品管理</template>
        </el-menu-item>

        <el-menu-item index="/merchant/orders">
          <el-icon><List /></el-icon>
          <template #title>订单管理</template>
        </el-menu-item>

        <el-menu-item index="/merchant/promotions">
          <el-icon><Discount /></el-icon>
          <template #title>促销管理</template>
        </el-menu-item>

        <el-menu-item index="/merchant/reviews">
          <el-icon><ChatLineRound /></el-icon>
          <template #title>评价管理</template>
        </el-menu-item>

        <el-menu-item index="/merchant/statistics">
          <el-icon><TrendCharts /></el-icon>
          <template #title>统计分析</template>
        </el-menu-item>
      </el-menu>

      <div class="sidebar-footer">
        <el-button
          type="primary"
          text
          @click="toggleCollapse"
          class="collapse-btn"
        >
          <el-icon>
            <Fold v-if="!isCollapse" />
            <Expand v-else />
          </el-icon>
          <span v-if="!isCollapse">收起菜单</span>
          <span v-else>展开菜单</span>
        </el-button>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="merchant-main">
      <!-- 顶部导航栏 -->
      <div class="merchant-header">
        <div class="header-left">
          <store-selector v-if="showStoreSelector" />
          <div v-else class="page-title">
            <h2>{{ pageTitle }}</h2>
          </div>
        </div>

        <div class="header-right">
          <el-button @click="toggleTheme" class="theme-toggle">
            <el-icon><Moon v-if="isDark" /><Sunny v-else /></el-icon>
          </el-button>

          <el-dropdown trigger="click">
            <div class="user-info">
              <el-avatar :size="32" :src="userAvatar">
                {{ userInitials }}
              </el-avatar>
              <span class="username">{{ username }}</span>
              <el-icon><CaretBottom /></el-icon>
            </div>

            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="goToProfile">
                  <el-icon><User /></el-icon>个人中心
                </el-dropdown-item>
                <el-dropdown-item divided @click="handleLogout">
                  <el-icon><SwitchButton /></el-icon>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="merchant-content">
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import "@/assets/styles/merchant-theme.css";
import { ref, computed, onMounted, defineComponent } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useThemeStore, useMerchantStore } from "@/store";
import { getUserProfile, logout } from "@/api";
import {
  clearAuth,
  removeToken,
  removeUserInfo,
  removeUserRole,
  getToken,
  isTokenExpired,
  isMerchant,
} from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";
import StoreSelector from "./StoreSelector.vue";
import {
  DataBoard,
  Shop,
  Collection,
  Goods,
  List,
  Discount,
  ChatLineRound,
  TrendCharts,
  User,
  SwitchButton,
  CaretBottom,
  Moon,
  Sunny,
  Fold,
  Expand,
} from "@element-plus/icons-vue";

export default defineComponent({
  name: "MerchantLayout",
  components: {
    StoreSelector,
    DataBoard,
    Shop,
    Collection,
    Goods,
    List,
    Discount,
    ChatLineRound,
    TrendCharts,
    User,
    SwitchButton,
    CaretBottom,
    Moon,
    Sunny,
    Fold,
    Expand,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const themeStore = useThemeStore();
    const merchantStore = useMerchantStore();

    // 侧边栏折叠状态
    const isCollapse = ref(false);

    // 切换侧边栏折叠状态
    const toggleCollapse = () => {
      isCollapse.value = !isCollapse.value;
    };

    // 用户信息
    const username = ref("");
    const userAvatar = ref("");

    // 当前激活的菜单
    const activeMenu = computed(() => route.path);

    // 页面标题
    const pageTitle = computed(() => {
      const routeMap: Record<string, string> = {
        "/merchant/dashboard": "仪表盘",
        "/merchant/store": "店铺管理",
        "/merchant/categories": "分类管理",
        "/merchant/products": "商品管理",
        "/merchant/orders": "订单管理",
        "/merchant/promotions": "促销管理",
        "/merchant/reviews": "评价管理",
        "/merchant/statistics": "统计分析",
        "/merchant/profile": "个人中心",
      };

      return routeMap[route.path] || "商家管理系统";
    });

    // 是否显示店铺选择器
    const showStoreSelector = computed(() => {
      // 在个人中心页面不显示店铺选择器
      return route.path !== "/merchant/profile";
    });

    // 用户头像首字母
    const userInitials = computed(() => {
      if (username.value) {
        return username.value.charAt(0).toUpperCase();
      }
      return "M";
    });

    // 是否是暗色主题
    const isDark = computed(() => themeStore.isDark);

    // 切换主题
    const toggleTheme = () => {
      // 由于这是商家端，我们只能在商家端的暗色和亮色之间切换
      themeStore.toggleTheme();
      // 确保应用商家端主题
      themeStore.applyMerchantTheme();
    };

    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        const res = await getUserProfile();
        const userData = res.data?.data || res.data;
        if (userData) {
          username.value = userData.username || "";
          userAvatar.value = userData.avatar || "";
        }
      } catch (error) {
        console.error("获取用户信息失败", error);
      }
    };

    // 跳转到个人中心
    const goToProfile = () => {
      router.push("/merchant/profile");
    };

    // 退出登录
    const handleLogout = () => {
      ElMessageBox.confirm("确定要退出登录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await logout();
            // 清除认证信息，但保留记住的用户名和密码
            removeToken();
            removeUserInfo();
            removeUserRole();
            ElMessage.success("退出登录成功");
            router.push("/merchant/login");
          } catch (error) {
            console.error("退出登录失败", error);
            // 即使API调用失败，也清除认证信息
            removeToken();
            removeUserInfo();
            removeUserRole();
            router.push("/merchant/login");
          }
        })
        .catch(() => {
          // 用户取消退出
        });
    };

    onMounted(() => {
      // 确保应用商家端主题
      themeStore.applyMerchantTheme();

      const initializeLayout = async () => {
        try {
          // 获取用户信息
          await fetchUserInfo();

          // 获取商家店铺列表
          if (merchantStore.stores.length === 0) {
            console.log("MerchantLayout: 初始化商家店铺列表");
            await merchantStore.fetchStores();
          } else {
            console.log(
              "MerchantLayout: 商家店铺列表已存在，数量:",
              merchantStore.stores.length
            );
          }

          // 确保当前店铺信息正确加载
          if (merchantStore.currentStoreId && !merchantStore.storeInfo?.id) {
            console.log(
              "MerchantLayout: 当前店铺ID存在但店铺信息不完整，重新设置当前店铺"
            );
            merchantStore.setCurrentStore(merchantStore.currentStoreId);
          }
        } catch (error) {
          console.error('MerchantLayout 初始化失败:', error);
        }
      };
      
      initializeLayout();
    });

    return {
      isCollapse,
      toggleCollapse,
      username,
      userAvatar,
      activeMenu,
      pageTitle,
      showStoreSelector,
      userInitials,
      isDark,
      toggleTheme,
      goToProfile,
      handleLogout,
    };
  },
});
</script>

<style scoped>
.merchant-layout {
  display: flex;
  min-height: 100vh;
  background-color: var(--bg-body);
}

.merchant-sidebar {
  position: fixed;
  height: calc(100vh - 10px); /* 减少一点高度，避免按钮被遮挡 */
  width: 220px;
  background-color: var(--bg-default);
  border-right: 1px solid var(--border-color);
  box-shadow: var(--shadow);
  z-index: 10;
  display: flex;
  flex-direction: column;
  transition: width 0.3s;
  overflow-y: auto;
  overflow-x: hidden;
}

.merchant-sidebar.is-collapsed {
  width: 64px;
}

.merchant-logo {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--secondary-dark);
  text-align: center;
  padding: 1rem 0;
  border-bottom: 1px solid var(--border-color);
  background-color: var(--bg-paper);
}

.merchant-logo a {
  text-decoration: none;
  color: inherit;
}

.merchant-logo span {
  color: var(--primary-dark);
}

.merchant-menu {
  flex: 1;
  border-right: none;
  background-color: var(--bg-default);
  padding-bottom: 60px; /* 为底部按钮留出空间 */
}

.merchant-menu :deep(.el-menu-item) {
  color: var(--text-primary) !important;
  transition: color 0.3s, padding 0.3s !important;
  background-color: transparent !important;
}

.merchant-menu :deep(.el-menu-item.is-active) {
  color: var(--secondary-dark) !important;
  background-color: rgba(255, 213, 79, 0.2) !important;
}

.merchant-menu :deep(.el-menu) {
  transition: width 0.3s !important;
  background-color: var(--bg-default) !important;
  border-right: none;
}

/* 禁用菜单项的背景过渡效果 */
.merchant-menu :deep(.el-menu--collapse .el-menu-item),
.merchant-menu :deep(.el-menu--collapse .el-sub-menu__title) {
  background-color: transparent !important;
}

/* 确保菜单折叠时不会有背景色闪烁 */
.merchant-menu :deep(.el-menu--collapse) {
  width: 64px !important;
}

.sidebar-footer {
  padding: 0.75rem;
  border-top: 1px solid var(--border-color);
  display: flex;
  justify-content: center;
  background-color: var(--bg-paper);
  position: fixed;
  bottom: 10px; /* 距离底部留出一些距离 */
  width: 220px; /* 与侧边栏宽度一致 */
  z-index: 11;
  transition: width 0.3s;
}

.is-collapsed .sidebar-footer {
  width: 64px;
}

.collapse-btn {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--secondary-dark) !important;
}

.collapse-btn .el-icon {
  margin-right: 4px;
}

.merchant-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-main);
  margin-left: 220px;
  transition: margin-left 0.3s;
}

.is-collapsed + .merchant-main {
  margin-left: 64px;
}

.merchant-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 1.5rem;
  height: 64px;
  background-color: var(--bg-default);
  border-bottom: 1px solid var(--border-color);
  box-shadow: var(--shadow-sm);
}

.header-left {
  display: flex;
  align-items: center;
}

.page-title h2 {
  margin: 0;
  font-size: 1.25rem;
  color: var(--secondary-dark);
}

.header-right {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.theme-toggle {
  padding: 0.5rem;
  border-radius: 50%;
  color: var(--secondary);
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0.25rem 0.5rem;
  border-radius: var(--radius);
  transition: var(--transition);
  color: var(--text-primary);
}

.user-info:hover {
  background-color: var(--bg-paper);
}

.username {
  margin: 0 0.5rem;
  font-weight: 500;
}

.merchant-content {
  flex: 1;
  padding: 1.5rem;
  overflow-y: auto;
  background-color: var(--bg-main);
}
</style>
